//
// Created by fuweicong on 2023/4/21.
//

#ifndef WEBRTC_PEER_CONNECT_CLIENT_H
#define WEBRTC_PEER_CONNECT_CLIENT_H

#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "json/json.h"
#include <unistd.h>
#include <thread>
#include "default.h"
#include "event2/event.h"
#include "event2/bufferevent.h"

namespace fm {
    bool GetHeaderValue(const std::string& data,
                        size_t eoh,
                        const char* header_pattern,
                        size_t* value);

    void writeData(struct bufferevent *bev, char *buffer, int size);

class CallbackMessage{
public:
    void message(int peer_id, const char* msg);
};

class PeerConnectClient {
    private:
        const int port = 8888;
        CallbackMessage *callbackMessage;
        struct event_base *base;
        struct bufferevent *bev;
        struct bufferevent *message_bev;
        // 连接服务器
        struct sockaddr_in serv_addr;
        const char* ip = "192.168.0.149";
        void send_message();
        void parse_peer_message(int peer, std::string message);
        bool ParseEntry(const std::string& entry,
                                           std::string* name,
                                           int* id,
                                           bool* connected);
        size_t content_length = 0;
        bool ParseServerResponse(const std::string& response,
                                                   size_t content_length,
                                                   size_t* peer_id,
                                                   size_t* eoh);

        int GetResponseStatus(const std::string& response);
        std::string data;
        int client_id = -1;
    public:
        PeerConnectClient(CallbackMessage *callbackMessage);
        void onRead(struct bufferevent *bev);
        void onMessageRead(struct bufferevent *bev);
        bool ReadIntoBuffer(struct bufferevent *bev, std::string &data);
        bool GetHeaderValue(const std::string& data,
                                               size_t eoh,
                                               const char* header_pattern,
                                               size_t* value);

        bool GetHeaderValue(const std::string& data,
                   size_t eoh,
                   const char* header_pattern,
                   std::string* value);
        void wait(struct bufferevent *bev, size_t id);
        void writeData(struct bufferevent *bev, char *buffer, int size);
        void sign(struct  bufferevent *ben);
        void sendMessage(int peer_id, const char* data);
        void read_message();
        void start();
};


}


#endif //WEBRTC_PEER_CONNECT_CLIENT_H
